<?php

namespace app\api\controller;

use app\common\model\Clients as M;

class Logins extends Base
{

    /**
     * 签到
     * @return \type
     */
    public function sign_in()
    {

        $username   = $client_id = input('username');
        $verifycode = input('verifycode');

        if ($verifycode == '123456') {

            $Client = new M();

            $client = $Client->_getWhere(['username' => $username]);
            if ($client) {

                add_clients_log($username, 'login');
                $client_data = $this->_oauth2Storage->getClientDetails($client_id);

                return js_return(1, 'login_success', $client_data);

            } else {

                $res = $Client->add([
                    'username'  => $username,
                    'tel'       => $username,
                    'create_at' => T(),
                    'update_at' => T(),
                ]);

                if ($res) {

                    add_clients_log($username, 'login');

                    $client_secret = randstr(8);
                    $grant_types   = 'client_credentials';
                    $redirect_uri  = '/api/logins/get_at';
                    $this->_oauth2Storage->setClientDetails($username, $client_secret, $redirect_uri, $grant_types);

                    return js_return(1, 'register success',
                        compact('client_id', 'client_secret', 'grant_types', 'redirect_uri'));
                }

                return js_return(0, 'server error, please retry');
            }


            return js_return(1, 'success', $res);

        } else {

            return js_return(0, 'verifycode error');
        }

    }


    public function logout()
    {
        cookie('managers_info');
        session('managers_info');
    }


    public function verify()
    {
        return js_return(1, "success", ['code' => "123456"]);
    }


    public function get_at()
    {
        $data = json_decode($this->fetchTokenResponseBody(), true);

        if (isset($data['error'])) {
            return js_return(0, $data['error'], $data);
        }

        return js_return(1, 'success', $data);
    }

}
